import { useAuthStore } from '../stores/auth'

export const authGuard = (to, from, next) => {
  const authStore = useAuthStore()
  
  // 恢复认证状态
  if (!authStore.isAuthenticated) {
    authStore.restoreAuth()
  }
  
  // 检查是否需要认证
  if (to.meta.requiresAuth && !authStore.isAuthenticated) {
    next('/login')
    return
  }
  
  // 检查是否已登录但访问登录/注册页面
  if ((to.path === '/login' || to.path === '/register') && authStore.isAuthenticated) {
    next('/')
    return
  }
  
  // 检查管理员权限
  if (to.meta.requiresAdmin && (!authStore.isAuthenticated || !authStore.isAdmin)) {
    next('/')
    return
  }
  
  next()
}

export const initAuth = () => {
  const authStore = useAuthStore()
  authStore.restoreAuth()
}